﻿using Microsoft.Extensions.FileProviders;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Extensions.Primitives;
using Microsoft.AspNetCore.Http;

namespace Service.Core.Files
{

    /// <summary>
    /// 授权文件提供程序
    /// </summary>
    /// <param name="innerProvider"></param>
    /// <param name="httpContextAccessor"></param>
    public class AuthorizedFileProvider(IFileProvider innerProvider, IHttpContextAccessor httpContextAccessor)
        : IFileProvider
    {

        public IDirectoryContents GetDirectoryContents(string subpath)
        {
            // 检查授权
            if (!IsAuthorized())
            {
                return new NotFoundDirectoryContents();
            }
            return innerProvider.GetDirectoryContents(subpath);
        }

        public IFileInfo GetFileInfo(string subpath)
        {
            if (!IsAuthorized())
            {
                return new NotFoundFileInfo(subpath);
            }
            return innerProvider.GetFileInfo(subpath);
        }

        public IChangeToken Watch(string filter)
        {
            return innerProvider.Watch(filter);
        }

        private bool IsAuthorized()
        {
            var context = httpContextAccessor.HttpContext;
            if (context == null) return false;
            // 这里实现你的授权逻辑
            return context.User.Identity?.IsAuthenticated ?? false;
        }

    }
}
